import React, { useState, useEffect } from 'react'
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  message, 
  Popconfirm,
  Tag,
  Tree,
  Switch,
  Spin
} from 'antd'
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  SafetyOutlined,
  ReloadOutlined 
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import roleService from '@/services/role'
import menuService from '@/services/menu'
import { MenuItem } from '@/types/menu'

const { TextArea } = Input

// 角色类型定义
interface Role {
  id: number
  roleName: string
  roleCode: string
  sort: number
  status: number
  remark?: string
  createTime: string
  updateTime?: string
  menuIds: number[]
  menus: MenuItem[]
}

const Roles: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false)
  const [roles, setRoles] = useState<Role[]>([])
  const [menus, setMenus] = useState<MenuItem[]>([])
  const [modalVisible, setModalVisible] = useState(false)
  const [permissionModalVisible, setPermissionModalVisible] = useState(false)
  const [editingRole, setEditingRole] = useState<Role | null>(null)
  const [selectedMenuIds, setSelectedMenuIds] = useState<number[]>([])
  const [form] = Form.useForm()

  // 获取角色列表
  const fetchRoles = async () => {
    try {
      setLoading(true)
      const response = await roleService.getRoles({})
      if (response.code === 200) {
        setRoles(response.data)
      } else {
        message.error(response.message || '获取角色列表失败')
      }
    } catch (error) {
      console.error('获取角色列表失败:', error)
      message.error('获取角色列表失败')
    } finally {
      setLoading(false)
    }
  }

  // 获取菜单列表
  const fetchMenus = async () => {
    try {
      const response = await menuService.getMenuList()
      if (response.code === 200) {
        setMenus(response.data)
      } else {
        message.error(response.message || '获取菜单列表失败')
      }
    } catch (error) {
      console.error('获取菜单列表失败:', error)
      message.error('获取菜单列表失败')
    }
  }

  useEffect(() => {
    fetchRoles()
    fetchMenus()
  }, [])

  // 表格列配置
  const columns: ColumnsType<Role> = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      ellipsis: true,
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      key: 'roleCode',
      ellipsis: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center',
      render: (status: number, record: Role) => (
        <Switch
          checked={status === 1}
          onChange={(checked) => handleStatusChange(record.id, checked ? 1 : 0)}
          size="small"
        />
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<SafetyOutlined />}
            onClick={() => handleAssignPermissions(record)}
          >
            分配权限
          </Button>
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个角色吗？"
            description="删除后将无法恢复"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  // 新增角色
  const handleAdd = () => {
    setEditingRole(null)
    setModalVisible(true)
    form.resetFields()
  }

  // 编辑角色
  const handleEdit = (role: Role) => {
    setEditingRole(role)
    setModalVisible(true)
    form.setFieldsValue({
      roleName: role.roleName,
      roleCode: role.roleCode,
      sort: role.sort,
      status: role.status,
      remark: role.remark,
    })
  }

  // 删除角色
  const handleDelete = async (id: number) => {
    try {
      const response = await roleService.deleteRole(id)
      if (response.code === 200) {
        message.success('删除成功')
        fetchRoles()
      } else {
        message.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除角色失败:', error)
      message.error('删除失败')
    }
  }

  // 状态切换
  const handleStatusChange = async (id: number, status: number) => {
    try {
      const response = await roleService.updateRoleStatus(id, status)
      if (response.code === 200) {
        message.success('状态更新成功')
        fetchRoles()
      } else {
        message.error(response.message || '状态更新失败')
      }
    } catch (error) {
      console.error('状态更新失败:', error)
      message.error('状态更新失败')
    }
  }

  // 分配权限
  const handleAssignPermissions = (role: Role) => {
    setEditingRole(role)
    setSelectedMenuIds(role.menuIds || [])
    setPermissionModalVisible(true)
  }

  // 保存角色
  const handleSave = async () => {
    try {
      const values = await form.validateFields()
      const roleData = {
        roleName: values.roleName,
        roleCode: values.roleCode,
        sort: values.sort || 0,
        status: values.status ?? 1,
        remark: values.remark,
        menuIds: [],
      }

      let response
      if (editingRole) {
        response = await roleService.updateRole(editingRole.id, roleData)
        if (response.code === 200) {
          message.success('更新成功')
        } else {
          message.error(response.message || '更新失败')
        }
      } else {
        response = await roleService.createRole(roleData)
        if (response.code === 200) {
          message.success('创建成功')
        } else {
          message.error(response.message || '创建失败')
        }
      }

      if (response.code === 200) {
        setModalVisible(false)
        form.resetFields()
        fetchRoles()
      }
    } catch (error) {
      console.error('保存角色失败:', error)
      message.error('保存失败')
    }
  }

  // 保存权限分配
  const handleSavePermissions = async () => {
    if (!editingRole) return

    try {
      const response = await roleService.assignRolePermissions({
        roleId: editingRole.id,
        menuIds: selectedMenuIds,
      })

      if (response.code === 200) {
        message.success('权限分配成功')
        setPermissionModalVisible(false)
        fetchRoles()
      } else {
        message.error(response.message || '权限分配失败')
      }
    } catch (error) {
      console.error('权限分配失败:', error)
      message.error('权限分配失败')
    }
  }

  // 构建菜单权限树数据
  const buildMenuTree = (menus: MenuItem[]): any[] => {
    return menus.map(menu => ({
      title: menu.name,
      key: menu.id || menu.key,
      children: menu.children ? buildMenuTree(menu.children) : undefined
    }))
  }

  const menuTreeData = buildMenuTree(menus)

  return (
    <Card 
      title="角色管理" 
      extra={
        <Space>
          <Button
            icon={<ReloadOutlined />}
            onClick={fetchRoles}
            loading={loading}
          >
            刷新
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增角色
          </Button>
        </Space>
      }
    >
      <Table
        columns={columns}
        dataSource={roles}
        rowKey="id"
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      {/* 角色编辑弹窗 */}
      <Modal
        title={editingRole ? '编辑角色' : '新增角色'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => {
          setModalVisible(false)
          form.resetFields()
        }}
        width={600}
        destroyOnHidden
      >
        <Form
          form={form}
          layout="vertical"
          autoComplete="off"
          initialValues={{
            sort: 0,
            status: 1,
          }}
        >
          <Form.Item
            label="角色名称"
            name="roleName"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          
          <Form.Item
            label="角色编码"
            name="roleCode"
            rules={[
              { required: true, message: '请输入角色编码' },
              { pattern: /^[a-zA-Z0-9_-]+$/, message: '只能包含字母、数字、下划线和横线' }
            ]}
          >
            <Input placeholder="请输入角色编码" disabled={!!editingRole} />
          </Form.Item>

          <Form.Item
            label="排序"
            name="sort"
            rules={[{ required: true, message: '请输入排序号' }]}
          >
            <Input type="number" placeholder="请输入排序号" />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            valuePropName="checked"
            getValueFromEvent={(checked) => checked ? 1 : 0}
            getValueProps={(value) => ({ checked: value === 1 })}
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
          
          <Form.Item
            label="备注"
            name="remark"
          >
            <TextArea rows={4} placeholder="请输入角色备注" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限分配弹窗 */}
      <Modal
        title={`分配权限 - ${editingRole?.roleName}`}
        open={permissionModalVisible}
        onOk={handleSavePermissions}
        onCancel={() => setPermissionModalVisible(false)}
        width={600}
        destroyOnHidden
      >
        <div style={{ marginBottom: 16 }}>
          <Tag color="blue">页面权限</Tag>
          <span style={{ color: '#666', fontSize: '12px' }}>选择角色可以访问的菜单页面</span>
        </div>
        <Tree
          checkable
          checkedKeys={selectedMenuIds}
          onCheck={(checkedKeys) => {
            setSelectedMenuIds(checkedKeys as number[])
          }}
          treeData={menuTreeData}
          height={400}
          defaultExpandAll
        />
      </Modal>
    </Card>
  )
}

export default Roles